package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.UserAuthMapper;
import com.heima.admin.service.UserAuthService;
import com.heima.apis.admin.IadminClient;
import com.heima.file.service.FileStorageService;
import com.heima.model.admin.dtos.AuthDto;
import com.heima.model.admin.dtos.AuthPageReqDto;
import com.heima.model.admin.pojos.AdAuth;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;

import java.util.Date;
import java.util.List;

/**
 * admin - 用户审核
 * @author yangkexuan
 * @className UserAuthServiceImpl
 * @date 2023/8/2 16:20
 * @description
 */
@Service
@Slf4j
public class UserAuthServiceImpl extends ServiceImpl<UserAuthMapper, AdAuth> implements UserAuthService {
    @Autowired
    private UserAuthMapper userAuthMapper;

    @Autowired
    private IadminClient iadminClient;

    @Autowired
    private AuthBaiduScanServiceImpl authBaiduScanService;

    @Autowired
    private FileStorageService fileStorageService;

    /**
     * 用户身份审核
     * @param dto
     * @return
     */
    @Override
    public ResponseResult userAuth(AuthPageReqDto dto) {
        //1. 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();


        //2.组装查询条件
        LambdaQueryWrapper<AdAuth> wrapper = Wrappers.<AdAuth>lambdaQuery();

        //2.1 处理状态条件
        if (dto.getStatus() != null) {
            wrapper.eq(AdAuth::getStatus, dto.getStatus());
        }

        //2.2 加入排序条件：按时间倒序
        wrapper.orderByDesc(AdAuth::getCreatedTime);

        //3. 进行条件分页查询
        IPage ipage = new Page(dto.getPage(), dto.getSize());
        page(ipage, wrapper);

        //4. 封装结果返回 当前页数据和总记录条数
        List list = ipage.getRecords();
        long total = ipage.getTotal();

        ResponseResult result = new PageResponseResult((int) ipage.getCurrent(),
                (int) ipage.getSize(), (int) total);

        result.setData(list);
        return result;
    }

    /**
     * 通过审核
     * @param id
     * @return
     */
    @Override
//    @GlobalTransactional
    public ResponseResult authPass(Long id) {
        // 参数校验
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdAuth adAuth = userAuthMapper.selectOne((Wrappers.<AdAuth>lambdaQuery().eq(AdAuth::getId,id)));
        if(adAuth == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //开始对接百度云的审核
        String resultFront = baiduyunExamimeFront(adAuth);
        if("false".equals(resultFront)){
            ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!"审核通过".equals(resultFront)){
            failFun(adAuth,resultFront);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        String resultBack = baiduyunExamimeBack(adAuth);
        if(!"审核通过".equals(resultBack)){
            failFun(adAuth,resultFront);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        adAuth.setStatus((short) 9)
                .setCheckTime(new Date())
                .setIsAccount(1);

        //更新状态
        userAuthMapper.updateById(adAuth);

        // 注册账号
        iadminClient.registerClient(adAuth);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 百度云审核-正面
     * @param adAuth
     */
    private String baiduyunExamimeFront(AdAuth adAuth) {
        // 审核正面照
        byte[] bytes = new byte[0];
        try {
            bytes = fileStorageService.downLoadFile(adAuth.getFontImage());
        } catch (Exception e) {
            e.printStackTrace();
            return "图片不合法";
        }
        String result = authBaiduScanService.idCardSide(bytes, "front");
        JSONObject json = JSONObject.parseObject(result);
        String imageStatus = json.getString("image_status");
        // 判断image_status的状态
        if(imageStatus == null && imageStatus == ""){
            return "false";
        }
        if(!imageStatus.equals("normal")){
            String status = pictureExamine(imageStatus);
            return status;
        }

        JSONObject wordsResult = json.getJSONObject("words_result");

        String name = wordsResult.getString("姓名");
        String idNum = wordsResult.getString("公民身份号码");
        //开始判断
        if(adAuth.getName().equals(name)){
            return "输入的姓名与身份证不符";
        }
        if(adAuth.getIdno().equals(idNum)){
            return "输入的姓名与身份证不符";
        }
        return "审核通过";
    }

    /**
     * 百度云审核-背面
     * @param adAuth
     * @return
     */
    private String baiduyunExamimeBack(AdAuth adAuth){
        String status = "";
        // 审核正面照
        byte[] bytes = new byte[0];
        try {
            bytes = fileStorageService.downLoadFile(adAuth.getBackImage());
        } catch (Exception e) {
            e.printStackTrace();
            return "图片不合法";
        }
        String result = authBaiduScanService.idCardSide(bytes, "back");
        JSONObject json = JSONObject.parseObject(result);
        String imageStatus = json.getString("image_status");
        if(!"normal".equals(imageStatus)){
            status = pictureExamine(imageStatus);
            return status;
        }
        return "审核通过";
    }

    /**
     * 审核失败
     * @param authDto
     * @return
     */
    @Override
    public ResponseResult authFail(AuthDto authDto) {
        Integer id = authDto.getId();
        String msg = authDto.getMsg();
        if (id == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        AdAuth adAuth = userAuthMapper.selectOne((Wrappers.<AdAuth>lambdaQuery().eq(AdAuth::getId,id)));
        if(adAuth == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 调用失败方法
        failFun(adAuth,msg);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 审核失败方法
     * @param adAuth
     * @param msg
     */
    private void failFun(AdAuth adAuth, String msg) {
        adAuth.setStatus((short) 2)
                .setCheckTime(new Date())
                .setReason(msg);
        userAuthMapper.updateById(adAuth);
    }

    /**
     * 返回查询内容
     * @param imageStatus
     * @return
     */
    private String pictureExamine(String imageStatus) {
        String status = "";
        switch (imageStatus) {
            case "reversed_side":
                status = "身份证正反面颠倒";
                break;
            case "non_idcard":
                status = "上传的图片中不包含身份证";
                break;
            case "blurred":
                status = "身份证模糊";
                break;
            case "other_type_card":
                status = "其他类型证照";
                break;
            case "over_exposure":
                status = "身份证关键字段反光或过曝";
                break;
            case "over_dark":
                status = "身份证欠曝（亮度过低）";
                break;
            case "unknown":
                status = "未知状态";
                break;
            default:
                status = "未知状态";
                break;
        }
        return status;
    }

}
